//
//  ClubStrategyDetailCell.swift
//  77Club
//
//  Created by Apple on 2024/9/5.
//

import UIKit

class ClubSquareDetailTopCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .white
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubSquareDetailTopPostItemCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 30.0.Scale
        tableView.layer.cornerRadius = 12.0.Scale
        tableView.layer.masksToBounds = true
        return tableView
    }()
    
    var jumpToDetail:((_:String, _ uid: String)->())?
    
    var models:[ClubGameCommunityListModel]? {
        didSet{
            guard let arr = models else { return }
            if arr.count >= 3 {
                tableView.heightConstraint?.constant = 90.0.Scale
            }else{
                tableView.heightConstraint?.constant = Double(arr.count) * 30.0.Scale
            }
            tableView.reloadData()
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initUI()
    }
    
    func initUI() -> Void {
        
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.clear
        
        contentView.subviews{
            tableView
        }
        tableView.leading(12.0.Scale).trailing(12.0.Scale).height(90.0.Scale).top(12.0.Scale).bottom(12.0.Scale)
    }
 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return models?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubSquareDetailTopPostItemCell", for: indexPath) as! ClubSquareDetailTopPostItemCell
        cell.model = models?[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        guard let md = models?[indexPath.row] else { return }        
        jumpToDetail?(md.id,md.uid)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

class ClubSquareDetailTitleHeaderView: UITableViewHeaderFooterView {
    
    private let titleLabel = c_make_ex(UILabel.self)
        .text("全部帖子").font(14.font_semiBold).color(.black).end()
    private let sortButton = c_make_ex(UIButton.self)
        .image("GameDetail_sortNor").image("GameDetail_sortSel", state: .selected).end()
    
    var updateData:((_:String)->())?
    
    var sortBy: String = "1" {
        didSet{
            sortButton.isSelected = (sortBy == "0")
        }
    }
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        backgroundColor = "#F7F8FA".toColor
        contentView.backgroundColor = "#F7F8FA".toColor
        
        initUI()
    }
    
    func initUI() -> Void {
        
        backgroundColor = UIColor.clear
        
        contentView.subviews{
            titleLabel
            sortButton
        }

        titleLabel.leading(12.0.Scale).top(0).bottom(0).centerVertically()
        sortButton.trailing(12.0.Scale).width(76.0.Scale).height(28.0.Scale).centerVertically()
        sortButton.addTarget(self, action: #selector(clickSortButton), for: .touchUpInside)
    }
    
    @objc private func clickSortButton(){
        
        let type = sortButton.isSelected ? "1" : "0"
        updateData?(type)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

}


class ClubSquareDetailTopItemCell: UITableViewCell {
    
    private let tagLabel = c_make_ex(UILabel.self)
        .border("#FF7500".toColor.alpha(0.5), width: 1)
        .color("#FF7500").corner(2).font(9.font_semiBold)
        .alignment(.center).end()
    private let contentLabel = c_make_ex(UILabel.self)
        .color("#2E3033").font(14.font_medium).end()
    private let rightImageView = c_make_ex(UIImageView.self)
        .mode(.scaleToFill).image("Square_detail_right").end()
    
    var model: ClubGameCommunityNewsModel?{
        didSet{
            guard let md = model else { return }
            tagLabel.text = md.type
            contentLabel.text = model?.title
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initUI()
    }
    
    func initUI() -> Void {
        
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.clear
        
        contentView.subviews{
            tagLabel
            contentLabel
            rightImageView
        }

        tagLabel.leading(16.0.Scale).width(26.0.Scale).height(14.0.Scale).centerVertically()
        rightImageView.trailing(16.0.Scale).size(14).centerVertically()
        contentLabel.leading(48.0.Scale).trailing(45.0.Scale).centerVertically()
    }
 

    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}


class ClubSquareDetailTopPostItemCell: UITableViewCell {
    
    private let tagImageV = c_make_ex(UIImageView.self)
        .image("Square_detail_top").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .color("#323233").font(14.font_medium).end()
    private let likeLabel = UIIconButton(style: .leading(itemSpace: 0))
    
    var model: ClubGameCommunityListModel?{
        didSet{
            guard let md = model else { return }
            titleLabel.text = md.title
            var good = md.good
            if good == "0" {
                good = ""
            }
            likeLabel.setTitle(good + "点赞", for: .normal)
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initUI()
    }
    
    func initUI() -> Void {
        
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.clear
        
        contentView.subviews{
            tagImageV
            titleLabel
            likeLabel
        }

        tagImageV.leading(12.0.Scale).width(26.0.Scale).height(14.0.Scale).centerVertically()
        likeLabel.trailing(12.0.Scale).height(14.0.Scale).centerVertically()
        titleLabel.leading(42.0.Scale).trailing(>=60.0.Scale).centerVertically()
//        titleLabel.Trailing >= likeLabel.Leading - 7.0.Scale
        likeLabel.Leading == titleLabel.Trailing + 3.0.Scale
        
        likeLabel.style { v in
            v.setImage("Square_detail_topLike".toImage, for: .normal)
            v.iconSize = CGSize(width: 14.0.Scale, height: 14.0.Scale)
            v.setTitleColor("#7D7E80".toColor, for: .normal)
            v.titleLabel?.font = 10.font_medium
            v.isUserInteractionEnabled = false
            v.contentHorizontalAlignment = .leading
        }
    }
 

    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}


class ClubForumDetailBottomView: UIView, RaeNetworkProtocol {
    
    let likeButton = UIIconButton(style: .top(itemSpace: 2))
    let collectButton = UIIconButton(style: .top(itemSpace: 2))
    private let shareButton = UIIconButton(style: .top(itemSpace: 2))
    private let commitButton = UIIconButton(style: .top(itemSpace: 2))
    private let textFiedlButton = c_make_ex(UIButton.self)
        .bgColor("#000000".toColor.alpha(0.05)).corner(16.0.Scale)
        .color("#7B7D80").font(11.font_medium).text("写点什么...").end()
    
    var showCommitView: (() -> Void)?
    var shareBlock: (() -> Void)?
    var likeBlock: (() -> Void)?

    var model:ClubGameCommunityDetailModel?{
        didSet{
            guard let md = model else { return }
            likeButton.isSelected = md.is_good
            var look = md.look
            if look == "0" {
                look = "浏览"
            }
            var like = md.good
            if like == "0" {
                like = "点赞"
            }
            var pinglun = md.pinglun
            if pinglun == "0"{
                pinglun = "评论"
            }
            likeButton.setTitle(like, for: .normal)
            collectButton.isSelected = md.is_shoucang == 1
            commitButton.setTitle(pinglun, for: .normal)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = "#FDFDFD".toColor
        
        subviews{
            shareButton
            likeButton
            collectButton
            commitButton
            textFiedlButton
        }
        
        shareButton.style { v in
            v.iconSize = CGSize(width: 24.0.Scale, height: 24.0.Scale)
            v.setImage("Square_detail_share".toImage, for: .normal)
            v.setTitle("分享", for: .normal)
            v.setTitleColor("#323233".toColor, for: .normal)
            v.titleLabel?.font = 10.font_medium
            v.addTarget(self, action: #selector(clickShareButton), for: .touchUpInside)
        }
        likeButton.style { v in
            v.iconSize = CGSize(width: 24.0.Scale, height: 24.0.Scale)
            v.setImage("Square_detail_like".toImage, for: .normal)
            v.setImage("Square_detail_liked".toImage, for: .selected)
            v.setTitle("点赞", for: .normal)
            v.setTitleColor("#2E3033".toColor, for: .normal)
            v.setTitleColor("#E65C6E".toColor, for: .selected)
            v.titleLabel?.font = 10.font_medium
            v.addTarget(self, action: #selector(clickLikeButton), for: .touchUpInside)
        }
        collectButton.style { v in
            v.iconSize = CGSize(width: 24.0.Scale, height: 24.0.Scale)
            v.setImage("Home_detail_collect".toImage, for: .normal)
            v.setImage("Home_detail_collected".toImage, for: .selected)
            v.setTitleColor("#2E3033".toColor, for: .normal)
            v.setTitleColor("#FF7600".toColor, for: .selected)
            v.setTitle("收藏", for: .normal)
            v.titleLabel?.font = 10.font_medium
            v.addTarget(self, action: #selector(clickCollectButton), for: .touchUpInside)
        }
        commitButton.style { v in
            v.iconSize = CGSize(width: 24.0.Scale, height: 24.0.Scale)
            v.setImage("Home_detail_commit".toImage, for: .normal)
            v.setTitle("评论", for: .normal)
            v.setTitleColor("#2E3033".toColor, for: .normal)
            v.titleLabel?.font = 10.font_medium
            v.addTarget(self, action: #selector(startCommit), for: .touchUpInside)
        }
        textFiedlButton.addTarget(self, action: #selector(startCommit), for: .touchUpInside)
        
        likeButton.height(40.0.Scale).width(44.0.Scale).trailing(12.0.Scale).top(11.0.Scale)
        collectButton.height(40.0.Scale).width(44.0.Scale).trailing(56.0.Scale)
        collectButton.CenterY == likeButton.CenterY
        commitButton.height(40.0.Scale).width(44.0.Scale).trailing(100.0.Scale)
        commitButton.CenterY == likeButton.CenterY
        shareButton.height(40.0.Scale).width(44.0.Scale).trailing(144.0.Scale)
        shareButton.CenterY == likeButton.CenterY
        textFiedlButton.leading(12.0.Scale).height(32.0.Scale).width(160.0.Scale).top(11.0.Scale)
        
    }
    
    @objc private func clickLikeButton(){
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            guard let infoId = model?.id else { return }
            Task{
                ToastUtil.show()
                let _ = await self.network.request(.likeStrategyPost(pid: infoId, puid: "", type: "0"),isShowError: false)
                ToastUtil.dismiss()
                likeButton.isSelected = !likeButton.isSelected
                likeBlock?()
                if likeButton.isSelected {
                    "点赞成功".toast_success
                }else{
                    "已取消点赞".toast_success
                }
            }
        }else{
            UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    @objc private func startCommit(){
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            showCommitView?()
        }else{
            UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }        
    }
    
    @objc private func clickShareButton(){
        shareBlock?()
    }
    
    @objc private func clickCollectButton(){
        
        if let id = model?.id {
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                Task {
                    let res = await network.requestSpecial(.collectForum(newsId: id),isShowError: false)
                    if res.isSuccess {
                        self.collectButton.isSelected = !self.collectButton.isSelected
                        if self.collectButton.isSelected {
                            "收藏成功".toast_success
                        }else{
                            "已取消收藏".toast_success
                        }
                    }
                }
            }else{
                UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
